<template>
  <view class="favorites">
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
    <view class="list" v-if="!is_empty">
      <view class="good_item" v-for="(item, index) in favoritesLists" :key="index">
        <navigator :url="'/pages/item/item?id=' + item.itemId + '&valueId=' + item.valueId + '&valueName=' + item.colorName" hover-class="none">
          <view class="image_box"><image :src="item.skuImageUrl" :style="{ height: imageHeight + 'rpx' }" /></view>
          <view class="textInfo">
            <strong>{{ item.itemName }}</strong>
            <p>款号：{{ item.frontCode }}</p>
            <p>颜色：{{ item.colorName }}</p>
            <p v-if="item.markingPrice / 1 > item.price / 1">
              价格：
              <text class="linePrice" v-if="item.markingPrice / 1 > 0">{{ '¥' + item.markingPrice }}</text>
              <text>{{ '¥' + item.price }}</text>
            </p>
            <p v-else>价格：{{ '¥' + item.price }}</p>
            <view class="markPrice rule-price-box" v-if="item.rulesArr.length > 0">
              <block v-for="(innerItem, innerIndex) in item.rulesArr" :key="innerIndex">
                <view class="rule-price goodsTag">{{ innerItem.priceTag}} {{ '¥ ' + innerItem.strategyPrice}}</view>
              </block>
            </view>
          </view>
        </navigator>
        <view class="btn_group">
          <view class="btn btn_pay" @click="goBuy" :data-itemId="item.itemId" :data-valueId="item.valueId" :data-valueName="item.colorName">立即购买</view>
          <view class="btn btn_check" @click="delFavorite" :data-favoritesId="item.favoritesId">删除</view>
        </view>
      </view>
    </view>

    <!-- 收藏数据为空时显示 -->
    <placeholder :is_empty.sync="is_empty" message="暂无收藏商品"></placeholder>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>
<script>
import Vue from 'vue';
import NavBar from '../../components/common/navbar';
import { MERCHANT_INFO, CUSTOMER_INFO, SYSTEM_INFO } from '../../utils/constant';
import Placeholder from '../../components/common/placeholder';
import api from '@/api/api';
export default {
  config: {
    navigationBarTitleText: '我的收藏',
    enablePullDownRefresh: false
  },
  components: {
    navBar: NavBar,
    placeholder: Placeholder
  },
  data() {
    return {
      isShowCustomNavBar: true,
      navbarData: {
        showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
        // title: '', //导航栏 中间的标题
        // hideHome:true
      },
      is_empty: false,
      showPlaceHolder: false,
      currentPage: 1, //当前页面
      pageTotal: 0, //总页数
      pageSize: 10, //每页个数
      favoritesLists: [], // 收藏列表,
      delSuccess: 0,
      preventRepeatReuqest: false, //防止重复加载
      jwt: '',
      previousPages: '',
      hasRule: false,
      imageHeight: 180,
	    listTotal: 0,
      nowPages:''
    };
  },
  onShow() {
    let that = this;
    that.currentPage = 1;
    let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    let jwt = customerInfo.jwt;
    that.jwt = customerInfo.jwt;
    if (getApp().globalData.refreshFavoritesList) {
      getApp().globalData.refreshFavoritesList = false
      that.getFavoriteListNew();
    } else {

    }
    getApp().cl_tracker.track('mini_program_view', {
          path:  this.nowPages,
          pageName: '我的收藏',
        })
  },
  onLoad() {
    if (!getApp().globalData.refreshFavoritesList) {
      this.getFavoriteList();
    }
    let pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    this.nowPages = currPage.route;
  },
  methods: {
		/**
		 * 展示弱提示
		 * @param {Object} msg 文案
		 */
		handleShowTextToast(msg){
			try{
				this.$refs.toastPopup.showToast(msg);
			}catch(e){}
		},
		/**
		 * 若提示按钮点击回调
		 * @param {Object} data.type 类型：confirm确定，cancel取消
		 * @param {Object} data.callBackData 呼气弹窗时传入的数据
		 */
		onToastPopupClick(data){},
    onPageScroll: function(e) {
      getApp().globalData.favoritePageScrollTop = e.scrollTop;
    },
    /**
     * 获取用户收藏列表
     */
    getFavoriteList: async function() {
      let that = this;
	  let customerInfo = uni.getStorageSync('customerInfo');
	  let memberDetails = uni.getStorageSync('memberDetails') || getApp().globalData.memberDetails
      if(getApp().globalData.favoriteListLength > 0 && getApp().globalData.favoriteListLength < that.listTotal && getApp().globalData.favoriteListLength % that.pageSize == 0) {
        that.currentPage = Math.ceil(getApp().globalData.favoriteListLength / that.pageSize) + 1
      // } else if (getApp().globalData.favoriteListLength > 0 && getApp().globalData.favoriteListLength >= that.listTotal) {
      //   return false
      // } else {

      }
      //获取商户信息
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
      const memberFavoriteList = await api.getFavoritesItems({
        method: 'GET',
        header: {
          jwt: uni.getStorageSync(CUSTOMER_INFO).jwt
        },
        query: {
          merchant_id: merchantInfo.cloudMerchantId,
          page_no: that.currentPage,
          page_size: that.pageSize,
          store_id: merchantInfo.cloudMerchantStoreId,
		  group_id: customerInfo.groupId || 0,
		  member_level_id: memberDetails.memberLevelId || 0,
		  member_status: memberDetails.isActive || 'Inactive'
        }
      });
      if (memberFavoriteList.code === 1000 && memberFavoriteList.data.content.length > 0) {
        that.favoritesLists = that.currentPage == 1 ? memberFavoriteList.data.content : [...that.favoritesLists, ...memberFavoriteList.data.content];
        that.favoritesLists = getApp().unique(that.favoritesLists)
        getApp().globalData.favoriteListLength = that.favoritesLists.length;
        that.pageTotal = Math.ceil(memberFavoriteList.data.total / that.pageSize);
        that.listTotal = memberFavoriteList.data.total
        let arr = getApp().unique(that.favoritesLists)
        for (var i in arr) {
          if(!!arr[i].strategies) {
            let result = await getApp().priceRulesDeal(arr[i].strategies)
            if(result.price !== 0) {
              arr[i].price = result.price
            }
            if(result.rulesArr.length > 0) {
              arr[i].rulesArr = result.rulesArr
            }
          }
        }
        that.favoritesLists = []
        that.favoritesLists = arr
        // that.getPriceRules();
        that.is_empty = false;
      } else {
        that.favoritesLists = [];
        that.is_empty = true;
      }
    },
    getFavoriteListNew: async function() {
      let that = this;
      //获取商户信息
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
	  let memberDetails = uni.getStorageSync('memberDetails') || getApp().globalData.memberDetails
      const memberFavoriteList = await api.getFavoritesItems({
        method: 'GET',
        header: {
          jwt: uni.getStorageSync(CUSTOMER_INFO).jwt
        },
        query: {
          merchant_id: merchantInfo.cloudMerchantId,
          page_no: 1,
          page_size: getApp().globalData.favoriteListLength,
          store_id: merchantInfo.cloudMerchantStoreId,
		  group_id: memberDetails.customerGroupId || 0,
		  member_level_id: memberDetails.memberLevelId || 0,
		  member_status: memberDetails.isActive || 'Inactive'
        }
      });
      if (memberFavoriteList.code === 1000 && memberFavoriteList.data.content.length > 0) {
        that.favoritesLists = memberFavoriteList.data.content;
        getApp().globalData.favoriteListLength = that.favoritesLists.length;
        that.listTotal = memberFavoriteList.data.total
        that.pageTotal = Math.ceil(memberFavoriteList.data.total / that.pageSize);
        // that.currentPage = that.favoritesLists.length < memberFavoriteList.data.total ? that.currentPage : i
        // that.getPriceRules();
        for (var i in that.favoritesLists) {
          if(!!that.favoritesLists[i].strategies) {
            let result = await getApp().priceRulesDeal(that.favoritesLists[i].strategies)
            if(result.price !== 0) {
              that.favoritesLists[i].price = result.price
            }
            if(result.rulesArr.length > 0) {
              that.favoritesLists[i].rulesArr = result.rulesArr
            }
          }
        }
        that.is_empty = false;
      } else {
        that.favoritesLists = [];
        that.is_empty = true;
      }
      setTimeout(function() {
        uni.pageScrollTo({
          scrollTop: getApp().globalData.favoritePageScrollTop,
          duration: 300
        });
      }, 200);
    },
    // 策略价格
    getPriceRules: async function(itemId, valueId) {
      let that = this;
      for (let index in that.favoritesLists) {
        const json = await api.getPriceRules(uni.getStorageSync(MERCHANT_INFO).cloudMerchantId, that.favoritesLists[index].itemId, that.favoritesLists[index].valueId);
        if (json.code === 1000) {
          let data = json.data;
          for (var i = 0; i < data.length; i++) {
            let now = new Date().getTime() / 1000;
            let start = new Date(data[i].strategyStartTime.replace(/-/g, '/')).getTime() / 1000;
            let end = new Date(data[i].strategyEndTime.replace(/-/g, '/')).getTime() / 1000;
            if (now - start >= 0 && end - now > 0) {
              that.favoritesLists[index].price = data[i].strategyPrice;
              that.hasRule = true;
              break;
            }
            if (i == data.length - 1 && !(now - start >= 0 && end - now > 0)) {
              this.hasRule = false;
            }
          }
        }
      }
    },

    // 删除商品收藏信息
    delFavoritesInfo: async function(favorites_id, index) {
      let that = this;
      let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
      const delfavorite = await api.delFavorites(
        {
          method: 'PUT',
          header: {
            jwt: uni.getStorageSync(CUSTOMER_INFO).jwt
          }
        },
        favorites_id
      );
      if (delfavorite.code == 1000) {
        this.handleShowTextToast('删除成功');
        getApp().globalData.favoritePageScrollTop = 0
        that.getFavoriteListNew();
      } else {
        this.handleShowTextToast('删除失败');
        //客户收藏信息不存在
      }
    },
    // 立即购买
    goBuy(e) {
      let that = this;
      let itemId = e.target.dataset.itemid;
      let valueId = e.target.dataset.valueid;
      let valueName = e.target.dataset.valuename;
      uni.navigateTo({
        url: '/pages/item/item?id=' + itemId + '&valueId=' + valueId + '&valueName=' + valueName
      });
    },
    // 删除收藏商品
    delFavorite(e) {
      let that = this;
      let favoritesId = e.target.dataset.favoritesid;
      let index = e.target.dataset.index;
      wx.showModal({
        content: '是否确认删除',
        success: function(res) {
          if (res.confirm) {
            that.delFavoritesInfo(favoritesId, index);
          } else if (res.cancel) {
        
          }
        }
      });
    },

    //加载更多
    onReachBottom() {
      let that = this;
      //判断总页数是否大于翻页数
      if (that.pageTotal > that.currentPage) {
        //防止重复加载
        if (that.preventRepeatReuqest) {
          return true;
        }
        that.preventRepeatReuqest = true;
        that.currentPage++;
        that.getFavoriteList();
        that.preventRepeatReuqest = false;
      } else {
        that.showLoading = false;
      }
    }
  }
};
</script>
<style lang="less">
/* 列表 */
.list {
  padding-bottom: 100rpx;
}
.good_item {
  justify-content: space-between;
  margin: 20rpx 20rpx 30rpx;
  padding: 16rpx 16rpx 10rpx;
  border: 2rpx solid #f1f1f1;
  display: block;
  overflow: hidden;
  position: relative;
}
.image_box {
  margin-right: 40rpx;
  min-height: 180rpx;
  float: left;
  image {
    width: 120rpx;
    display: block;
  }
}

.product_name {
  color: #414141;
  font-size: 32rpx;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  word-break: break-all;
}

.product_rule {
  font-size: 26rpx;
  color: #757575;
  padding-top: 16rpx;
  display: none;
}

.price {
  color: #de0000;
  font-size: 34rpx;
  font-weight: 600;
}
.linePrice {
  text-decoration: line-through;
  padding-right: 20rpx;
  color: #cccccc;
}

.goods {
  padding: 0;
  float: right;
  .order_footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 20rpx;
  }
  .order_state {
    color: #ff4856;
    font-size: 32rpx;
  }
  .btn_group {
    display: flex;
    align-items: right;
    .btn {
      font-size: 25rpx;
      padding: 10rpx 10rpx;
      text-align: center;
      margin: 0 auto;
      width: 100%;
    }
    .btn_del {
      color: #333;
      border: 1px solid #ccc;
    }
  }
}

.product_info {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
}
.cost_price {
  padding-left: 20rpx;
}
.textInfo {
  display: flex;
  flex-flow: column wrap;
}
.textInfo strong {
  font-size: 26rpx;
  margin: 2px 0 5px;
  font-weight: normal;
  display: block;
  line-height: 40rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; // 控制多行的行数
  -webkit-box-orient: vertical;
}
.textInfo p {
  height: 40rpx;
  line-height: 40rpx;
  display: block;
  font-size: 26rpx;
}
.product_info {
  display: block;
  position: absolute;
  top: 6rpx;
  right: 20rpx;
}
.product_info .price,
.product_info .goods_num {
  text-align: right;
  font-size: 28rpx;
  font-weight: normal;
  color: #444;
}
.product_info .goods_num {
  color: #bbb;
}
.os_text {
  font-size: 12px;
}
.rma_state span {
  float: right;
  text-decoration: underline;
}
.btn_group {
  display: flex;
  width: 100%;
  flex-direction: row-reverse;
  border-top: 2rpx solid #f1f1f1;
  margin-top: 26rpx;
  padding-top: 10rpx;
}

.btn_group .btn {
  padding: 6rpx;
  width: 25%;
  border: 1rpx solid #999;
  margin-left: 20rpx;
  line-height: 42rpx;
}
.btn_group .btn_check {
  color: #444;
  border: 1rpx solid #cccccc;
  background-color: #fff;
}
.goodsTag {
  color: #ff571a;
}
</style>
